package com.qin.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.log.StaticLog;

/**
 * 拿到条形验证码
 */
@WebServlet("/linecaptcha")
public class LineCaptchaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//定义图形验证码的长和宽
		LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);

		 
		// 把code放在session域中
		 HttpSession session = request.getSession();
		 session.setAttribute("lineCaptcha", lineCaptcha.getCode());
		 StaticLog.debug("图片中真正的验证码：{}", lineCaptcha.getCode());
		 
		 // 拼接独一的URL地址
		 String captchaUrl = "/lineCaptcha/"+IdUtil.objectId()+".png";
		 String captchaUrlPlus = request.getSession().getServletContext().getRealPath("")+captchaUrl;
		 
		 StaticLog.debug("图片独一的网络地址：{}", request.getContextPath()+captchaUrl);
		 StaticLog.debug("拼接后独一的图片文件路径：{}", captchaUrlPlus);
		 // 放到本地服务器上
		 lineCaptcha.write(captchaUrlPlus);
		 
		 // 把图片的地址响应出去
		 response.getOutputStream().print(request.getContextPath()+captchaUrl);
	}
}
